package com.lidx.back.statistics.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lidx.back.statistics.commons.PageInfo;
import com.lidx.back.statistics.dao.ILogDao;
import com.lidx.back.statistics.entity.Log;
import com.lidx.back.statistics.utils.StringUtils;
@Repository(value="logDao")
public class LogDaoImpl implements ILogDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession(){
		if(sessionFactory.getCurrentSession() == null){
			return sessionFactory.openSession();
		}
		return sessionFactory.getCurrentSession();
	}
	
	public void saveLog(Log log) {
		getSession().save(log);
	}

	public List<Log> getLogList(String from, String to) {
		StringBuilder sb = new StringBuilder("from Log where 1= 1");
		if(StringUtils.isNotBlank(from) && StringUtils.isNotBlank(to)){
			sb.append(" and createDate >= '").append(from).append("' and createDate <= '").append(to).append("'");
		}
		sb.append("order by createDate desc");
		List list = getSession().createQuery(sb.toString()).list();
		if(list.size()>0){
			return list;
		}
		return null;
	}

	public PageInfo findLogPage(int pageSize, int pageNo, String from, String to) {
		StringBuilder sb = new StringBuilder("from Log where 1= 1");
		if(StringUtils.isNotBlank(from) && StringUtils.isNotBlank(to)){
			sb.append(" and createDate >= '").append(from).append("' and createDate <= '").append(to).append("'");
		}
		sb.append("order by createDate desc");
		Query query = getSession().createQuery(sb.toString());
		final int offset = PageInfo.countOffset(pageSize, pageNo);
		query.setFirstResult(offset);
		query.setMaxResults(pageSize);
		List list = query.list();
		PageInfo pageInfo = new PageInfo();
		pageInfo.setPageNo(pageNo);
		pageInfo.setPageSize(pageSize);
		pageInfo.setList(list);
		long allRow = queryLogPageCount();
		pageInfo.setAllRow(allRow);
		pageInfo.setTotalPage(PageInfo.countTotalPage(pageSize, allRow));
		return pageInfo;
	}
	
	private long queryLogPageCount() {
		Query query = getSession().createQuery("select count(1) from Log");
		return  (Long) query.list().get(0);
	}

}
